<template>
<div class="follows-message-container">
    <!-- 使用通用导航栏组件 -->
    <tab-nav-bar :tabs="navTabs" :active-tab="activeTab" @click-left="$router.back()" @tab-change="switchTab" />

    <!-- 搜索框 -->
    <div class="search-box">
        <van-search v-model="searchText" :placeholder="searchPlaceholder" shape="round" background="#f7f8fa" />
    </div>

    <!-- 内容区域 -->
    <div class="tab-content">
        <!-- 点赞 -->
        <div v-show="activeTab === 'likes'" class="tab-pane">
            <van-pull-refresh v-model="likesRefreshing" @refresh="onLikesRefresh">
                <van-list v-model:loading="likesLoading" :finished="!likesHasMore" finished-text="没有更多了"
                    @load="fetchLikesList">
                    <div class="message-list">
                        <message-item v-for="(item, index) in likesList" :key="index" type="user" :avatar="item.avatar"
                            :title="item.nickname" :time="item.time" :message="item.content" :show-post-preview="true"
                            :post-image="item.postImage" :post-title="item.postTitle"
                            @click="goToUserProfile(item.userId)" @post-click="goToPost(item.postId)" />

                        <!-- 无数据提示 -->
                        <div class="empty-list" v-if="likesList.length === 0 && !likesLoading">
                            <van-empty description="暂无点赞消息" />
                        </div>
                    </div>
                </van-list>
            </van-pull-refresh>
        </div>

        <!-- 评论 -->
        <div v-show="activeTab === 'comments'" class="tab-pane">
            <van-pull-refresh v-model="commentsRefreshing" @refresh="onCommentsRefresh">
                <van-list v-model:loading="commentsLoading" :finished="!commentsHasMore" finished-text="没有更多了"
                    @load="fetchCommentsList">
                    <div class="message-list">
                        <message-item v-for="(item, index) in commentsList" :key="index" type="user"
                            :avatar="item.avatar" :title="item.nickname" :time="item.time" :message="item.content"
                            :show-post-preview="true" :post-image="item.postImage" :post-title="item.postTitle"
                            @click="goToUserProfile(item.userId)" @post-click="goToPost(item.postId)" />

                        <!-- 无数据提示 -->
                        <div class="empty-list" v-if="commentsList.length === 0 && !commentsLoading">
                            <van-empty description="暂无评论消息" />
                        </div>
                    </div>
                </van-list>
            </van-pull-refresh>
        </div>

        <!-- 新粉丝 -->
        <div v-show="activeTab === 'followers'" class="tab-pane">
            <van-pull-refresh v-model="followersRefreshing" @refresh="onFollowersRefresh">
                <van-list v-model:loading="followersLoading" :finished="!followersHasMore" finished-text="没有更多了"
                    @load="fetchFollowersList">
                    <div class="message-list">
                        <message-item v-for="(item, index) in followersList" :key="index" type="user"
                            :avatar="item.avatar" :title="item.nickname" :time="item.time" message="关注了你"
                            :show-action="true" :action-status="item.isFollowed" @click="goToUserProfile(item.userId)"
                            @action-click="toggleFollow(item)" />

                        <!-- 无数据提示 -->
                        <div class="empty-list" v-if="followersList.length === 0 && !followersLoading">
                            <van-empty description="暂无新粉丝" />
                        </div>
                    </div>
                </van-list>
            </van-pull-refresh>
        </div>

        <!-- 通知 -->
        <div v-show="activeTab === 'notices'" class="tab-pane">
            <van-pull-refresh v-model="noticesRefreshing" @refresh="onNoticesRefresh">
                <van-list v-model:loading="noticesLoading" :finished="!noticesHasMore" finished-text="没有更多了"
                    @load="fetchNoticesList">
                    <div class="message-list">
                        <message-item v-for="(item, index) in noticesList" :key="index" type="notice" :icon="item.icon"
                            :title="item.title" :time="item.time" :message="item.content" @click="readNotice(item)" />

                        <!-- 无数据提示 -->
                        <div class="empty-list" v-if="noticesList.length === 0 && !noticesLoading">
                            <van-empty description="暂无通知" />
                        </div>
                    </div>
                </van-list>
            </van-pull-refresh>
        </div>
    </div>
</div>
</template>

<script>
import TabNavBar from '@/components/TabNavBar.vue'
import MessageItem from '@/components/message/MessageItem.vue'

export default {
    name: 'FollowsMessagePage',
    components: {
        TabNavBar,
        MessageItem
    },
    data() {
        return {
            activeTab: 'likes', // 默认显示点赞
            searchText: '', // 搜索文本

            // 导航栏选项卡数据
            navTabs: [
                { label: '点赞', value: 'likes' },
                { label: '评论', value: 'comments' },
                { label: '新粉丝', value: 'followers' },
                { label: '通知', value: 'notices' }
            ],

            // 点赞列表
            likesList: [],
            likesHasMore: true,
            likesPage: 1,
            likesLoading: false,
            likesRefreshing: false,

            // 评论列表
            commentsList: [],
            commentsHasMore: true,
            commentsPage: 1,
            commentsLoading: false,
            commentsRefreshing: false,

            // 新粉丝列表
            followersList: [],
            followersHasMore: true,
            followersPage: 1,
            followersLoading: false,
            followersRefreshing: false,

            // 通知列表
            noticesList: [],
            noticesHasMore: true,
            noticesPage: 1,
            noticesLoading: false,
            noticesRefreshing: false
        }
    },
    computed: {
        // 搜索框占位符
        searchPlaceholder() {
            switch (this.activeTab) {
                case 'likes':
                    return '搜索点赞消息'
                case 'comments':
                    return '搜索评论消息'
                case 'followers':
                    return '搜索新粉丝'
                case 'notices':
                    return '搜索通知'
                default:
                    return '搜索消息'
            }
        }
    },
    created() {
        // 根据路由参数设置当前标签
        const path = this.$route.path
        if (path.includes('/message/')) {
            const tab = path.split('/message/')[1]
            if (['likes', 'comments', 'followers', 'notices'].includes(tab)) {
                this.activeTab = tab
            }
        }

        // 加载当前标签的数据
        this.loadCurrentTabData()
    },
    methods: {
        // 切换标签
        switchTab(tab) {
            if (this.activeTab === tab) return
            this.activeTab = tab
            this.searchText = ''

            // 更新路由，但不重新加载页面
            this.$router.push(`/message/${tab}`)

            // 加载当前标签的数据
            this.loadCurrentTabData()
        },

        // 加载当前标签的数据
        loadCurrentTabData() {
            switch (this.activeTab) {
                case 'likes':
                    if (this.likesList.length === 0) {
                        this.fetchLikesList()
                    }
                    break
                case 'comments':
                    if (this.commentsList.length === 0) {
                        this.fetchCommentsList()
                    }
                    break
                case 'followers':
                    if (this.followersList.length === 0) {
                        this.fetchFollowersList()
                    }
                    break
                case 'notices':
                    if (this.noticesList.length === 0) {
                        this.fetchNoticesList()
                    }
                    break
            }
        },

        // 跳转到用户主页
        goToUserProfile(userId) {
            this.$router.push(`/user/${userId}`)
        },

        // 跳转到帖子详情
        goToPost(postId) {
            this.$router.push(`/post/${postId}`)
        },

        // 切换关注状态
        toggleFollow(user) {
            user.isFollowed = !user.isFollowed
        },

        // 获取点赞列表
        async fetchLikesList() {
            if ((this.likesList.length > 0 && !this.likesHasMore)) return

            try {
                // 模拟API请求
                setTimeout(() => {
                    // 模拟数据
                    const mockData = Array(10).fill().map((_, index) => ({
                        userId: `user_${this.likesPage}_${index}`,
                        nickname: `用户${this.likesPage}_${index}`,
                        avatar: 'https://img01.yzcdn.cn/vant/cat.jpeg',
                        time: '2小时前',
                        content: '赞了你的笔记',
                        postId: `post_${index}`,
                        postImage: 'https://img01.yzcdn.cn/vant/leaf.jpg',
                        postTitle: `这是一篇测试笔记 ${this.likesPage}_${index}`
                    }))

                    this.likesList = [...this.likesList, ...mockData]
                    this.likesPage += 1
                    this.likesHasMore = this.likesPage < 5 // 模拟有5页数据
                    this.likesLoading = false
                }, 1000)
            } catch (error) {
                console.error('获取点赞消息失败', error)
                this.likesLoading = false
            }
        },

        // 获取评论列表
        async fetchCommentsList() {
            if ((this.commentsList.length > 0 && !this.commentsHasMore)) return

            try {
                // 模拟API请求
                setTimeout(() => {
                    // 模拟数据
                    const mockData = Array(10).fill().map((_, index) => ({
                        userId: `user_${this.commentsPage}_${index}`,
                        nickname: `用户${this.commentsPage}_${index}`,
                        avatar: 'https://img01.yzcdn.cn/vant/cat.jpeg',
                        time: '3小时前',
                        content: `这是一条评论内容，评论了你的笔记 ${this.commentsPage}_${index}`,
                        postId: `post_${index}`,
                        postImage: 'https://img01.yzcdn.cn/vant/leaf.jpg',
                        postTitle: `这是一篇测试笔记 ${this.commentsPage}_${index}`
                    }))

                    this.commentsList = [...this.commentsList, ...mockData]
                    this.commentsPage += 1
                    this.commentsHasMore = this.commentsPage < 5 // 模拟有5页数据
                    this.commentsLoading = false
                }, 1000)
            } catch (error) {
                console.error('获取评论消息失败', error)
                this.commentsLoading = false
            }
        },

        // 获取新粉丝列表
        async fetchFollowersList() {
            if ((this.followersList.length > 0 && !this.followersHasMore)) return

            try {
                // 模拟API请求
                setTimeout(() => {
                    // 模拟数据
                    const mockData = Array(10).fill().map((_, index) => ({
                        userId: `user_${this.followersPage}_${index}`,
                        nickname: `新粉丝${this.followersPage}_${index}`,
                        avatar: 'https://img01.yzcdn.cn/vant/cat.jpeg',
                        time: '1天前',
                        isFollowed: index % 2 === 0 // 一半已关注
                    }))

                    this.followersList = [...this.followersList, ...mockData]
                    this.followersPage += 1
                    this.followersHasMore = this.followersPage < 5 // 模拟有5页数据
                    this.followersLoading = false
                }, 1000)
            } catch (error) {
                console.error('获取新粉丝失败', error)
                this.followersLoading = false
            }
        },

        // 获取通知列表
        async fetchNoticesList() {
            if ((this.noticesList.length > 0 && !this.noticesHasMore)) return

            try {
                // 模拟API请求
                setTimeout(() => {
                    // 模拟数据
                    const noticeTypes = ['gift', 'star', 'like', 'setting']
                    const noticeIcons = ['gift-o', 'gem-o', 'like-o', 'setting-o']
                    const noticeTitles = ['礼品通知', '活动公告', '系统提醒', '设置变更']

                    const mockData = Array(10).fill().map((_, index) => {
                        const typeIndex = index % 4
                        return {
                            id: `notice_${this.noticesPage}_${index}`,
                            type: noticeTypes[typeIndex],
                            icon: noticeIcons[typeIndex],
                            title: noticeTitles[typeIndex],
                            content: `这是一条系统通知内容 ${this.noticesPage}_${index}`,
                            time: '2天前',
                            isRead: index % 3 === 0 // 三分之一已读
                        }
                    })

                    this.noticesList = [...this.noticesList, ...mockData]
                    this.noticesPage += 1
                    this.noticesHasMore = this.noticesPage < 5 // 模拟有5页数据
                    this.noticesLoading = false
                }, 1000)
            } catch (error) {
                console.error('获取通知失败', error)
                this.noticesLoading = false
            }
        },

        // 阅读通知
        readNotice(notice) {
            // 如果通知未读，则标记为已读
            if (!notice.isRead) {
                notice.isRead = true
                // 这里可以调用API将通知标记为已读
                // await noticeApi.markAsRead(notice.id)
            }

            // 根据通知类型处理相应的跳转
            switch (notice.type) {
                case 'gift':
                    this.$router.push('/gifts')
                    break
                case 'star':
                    this.$router.push('/activities')
                    break
                case 'like':
                    this.$router.push('/likes')
                    break
                case 'setting':
                    this.$router.push('/settings')
                    break
                default:
                    // 默认不跳转
                    break
            }
        },

        // 重置点赞列表并刷新
        onLikesRefresh() {
            // 重置数据
            this.likesList = []
            this.likesPage = 1
            this.likesHasMore = true

            // 获取数据
            this.fetchLikesList().then(() => {
                this.likesRefreshing = false
            })
        },

        // 重置评论列表并刷新
        onCommentsRefresh() {
            // 重置数据
            this.commentsList = []
            this.commentsPage = 1
            this.commentsHasMore = true

            // 获取数据
            this.fetchCommentsList().then(() => {
                this.commentsRefreshing = false
            })
        },

        // 重置粉丝列表并刷新
        onFollowersRefresh() {
            // 重置数据
            this.followersList = []
            this.followersPage = 1
            this.followersHasMore = true

            // 获取数据
            this.fetchFollowersList().then(() => {
                this.followersRefreshing = false
            })
        },

        // 重置通知列表并刷新
        onNoticesRefresh() {
            // 重置数据
            this.noticesList = []
            this.noticesPage = 1
            this.noticesHasMore = true

            // 获取数据
            this.fetchNoticesList().then(() => {
                this.noticesRefreshing = false
            })
        }
    }
}
</script>

<style scoped>
.follows-message-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    background-color: #f7f8fa;
}

.search-box {
    padding: 8px 16px;
    background-color: #fff;
    position: sticky;
    top: 46px;
    z-index: 10;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.tab-content {
    flex: 1;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
    /* 增强iOS滚动体验 */
}

.tab-pane {
    padding-bottom: 60px;
    min-height: calc(100vh - 106px);
    /* 屏幕高度减去顶部导航和搜索框 */
}

.message-list {
    background-color: #fff;
    padding: 0 16px;
}

/* 添加下拉刷新自定义样式 */
:deep(.van-pull-refresh) {
    overflow: visible;
}

:deep(.van-pull-refresh__track) {
    min-height: calc(100vh - 106px);
}

/* 添加列表加载样式 */
:deep(.van-list__finished-text) {
    color: #999;
    font-size: 13px;
    padding: 16px 0;
}

:deep(.van-list__loading) {
    padding: 16px 0;
}

.empty-list {
    padding: 60px 0;
}

/* 适配暗黑模式 */
@media (prefers-color-scheme: dark) {
    .follows-message-container {
        background-color: #121212;
    }

    .search-box {
        background-color: #1e1e1e;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
    }

    .message-list {
        background-color: #1e1e1e;
    }

    :deep(.van-search) {
        background-color: #1e1e1e !important;
    }

    :deep(.van-search__content) {
        background-color: #2d2d2d !important;
    }

    :deep(.van-empty__description) {
        color: #aaa;
    }
}

/* 适配平板和桌面屏幕 */
@media (min-width: 768px) {
    .follows-message-container {
        max-width: 600px;
        margin: 0 auto;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
    }
}
</style>